<template>
    <div class="code-editor-container">
        <div class="editor-header">
            <div class="file-info">
                <el-input v-model="currentFilePath" placeholder="输入文件路径，如: /path/to/MyTask.java" class="file-path-input"
                    @change="handleFilePathChange">
                    <template #prepend>
                        <el-icon>
                            <Folder />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <div class="editor-actions">
                <el-button @click="handleLoad" :loading="loading">
                    <el-icon>
                        <FolderOpened />
                    </el-icon>
                    加载
                </el-button>
                <el-button type="primary" @click="handleSave" :loading="saving">
                    <el-icon>
                        <Document />
                    </el-icon>
                    保存
                </el-button>
                <el-button type="success" @click="handleCompile" :loading="compiling">
                    <el-icon>
                        <Tools />
                    </el-icon>
                    编译
                </el-button>
                <el-button @click="handleClear">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    清空
                </el-button>
            </div>
        </div>

        <!-- 代码编辑器 -->
        <div class="editor-wrapper">
            <div ref="editorContainer" class="monaco-editor"></div>
        </div>

        <!-- 快速模板 -->
        <div class="template-selector">
            <el-select v-model="selectedTemplate" placeholder="选择模板" @change="handleTemplateChange"
                style="width: 200px">
                <el-option v-for="template in templates" :key="template.value" :label="template.label"
                    :value="template.value" />
            </el-select>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Folder, FolderOpened, Document, Tools, Delete } from '@element-plus/icons-vue'
import * as monaco from 'monaco-editor'
import { fileApi } from '@/api/files'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    filePath: {
        type: String,
        default: ''
    },
    height: {
        type: String,
        default: '400px'
    }
})

const emit = defineEmits(['update:modelValue', 'update:filePath', 'saved', 'compiled'])

// 响应式数据
const editorContainer = ref()
const currentFilePath = ref(props.filePath)
const loading = ref(false)
const saving = ref(false)
const compiling = ref(false)
const selectedTemplate = ref('')

let editor = null

// 代码模板
const templates = ref([
    { label: '选择模板', value: '' },
    { label: 'Hello World 任务', value: 'helloWorld' },
    { label: '数据处理任务', value: 'dataProcessing' },
    { label: '系统监控任务', value: 'systemMonitor' },
    { label: '空白Java类', value: 'blank' }
])

// 模板代码
const templateCodes = {
    helloWorld: `package com.example.tasks;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Hello World 任务示例
 */
public class HelloWorldTask {
    
    /**
     * 简单的Hello World方法
     */
    public String sayHello() {
        String message = "Hello World! 当前时间: " + 
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("[HelloWorldTask] " + message);
        return message;
    }
    
    /**
     * 带参数的Hello方法
     */
    public String sayHelloTo(String name) {
        String message = "Hello " + name + "! 当前时间: " + 
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("[HelloWorldTask] " + message);
        return message;
    }
}`,

    dataProcessing: `package com.example.tasks;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 数据处理任务示例
 */
public class DataProcessingTask {
    
    /**
     * 数据备份方法
     */
    public String backupData() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String message = "数据备份任务执行完成，备份时间: " + timestamp;
        System.out.println("[DataProcessingTask] " + message);
        
        // 模拟备份过程
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        return message;
    }
    
    /**
     * 数据处理方法
     */
    public String processData(String input) {
        String result = "处理数据: " + input + " 在 " + LocalDateTime.now();
        System.out.println("[DataProcessingTask] " + result);
        return result;
    }
}`,

    systemMonitor: `package com.example.tasks;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 系统监控任务示例
 */
public class SystemMonitorTask {
    
    /**
     * 健康检查方法
     */
    public String healthCheck() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        // 模拟系统检查
        long freeMemory = Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();
        double memoryUsage = (double)(totalMemory - freeMemory) / totalMemory * 100;
        
        String result = String.format("[%s] 系统健康检查完成 - 内存使用率: %.2f%%", 
            timestamp, memoryUsage);
        
        System.out.println("[SystemMonitorTask] " + result);
        return result;
    }
    
    /**
     * 资源监控方法
     */
    public String monitorResources() {
        String message = "系统资源监控完成: " + LocalDateTime.now();
        System.out.println("[SystemMonitorTask] " + message);
        return message;
    }
}`,

    blank: `package com.example.tasks;

import java.time.LocalDateTime;

/**
 * 自定义任务类
 */
public class CustomTask {
    
    /**
     * 执行任务方法
     */
    public String execute() {
        String message = "任务执行完成: " + LocalDateTime.now();
        System.out.println("[CustomTask] " + message);
        return message;
    }
}`
}

// 初始化编辑器
const initEditor = () => {
    if (editorContainer.value) {
        editor = monaco.editor.create(editorContainer.value, {
            value: props.modelValue || '',
            language: 'java',
            theme: 'vs-dark',
            fontSize: 14,
            fontFamily: 'Monaco, "Courier New", monospace',
            lineNumbers: 'on',
            roundedSelection: false,
            scrollBeyondLastLine: false,
            minimap: { enabled: true },
            automaticLayout: true,
            tabSize: 4,
            insertSpaces: true,
            wordWrap: 'on',
            lineHeight: 20,
            letterSpacing: 0,
            cursorStyle: 'line',
            cursorBlinking: 'blink',
            renderLineHighlight: 'line',
            selectOnLineNumbers: true,
            glyphMargin: true,
            folding: true,
            foldingStrategy: 'auto',
            showFoldingControls: 'always',
            disableLayerHinting: false,
            fixedOverflowWidgets: true
        })

        // 监听内容变化
        editor.onDidChangeModelContent(() => {
            const value = editor.getValue()
            emit('update:modelValue', value)
        })

        // 强制重新布局
        setTimeout(() => {
            if (editor) {
                editor.layout()
            }
        }, 100)
    }
}

// 加载文件
const handleLoad = async () => {
    if (!currentFilePath.value.trim()) {
        ElMessage.warning('请输入文件路径')
        return
    }

    loading.value = true
    try {
        const response = await fileApi.readFile(currentFilePath.value)
        const content = response.data.content

        if (editor) {
            editor.setValue(content)
        }

        emit('update:filePath', currentFilePath.value)
        ElMessage.success('文件加载成功')

    } catch (error) {
        ElMessage.error('加载文件失败')
        console.error('加载文件失败:', error)
    } finally {
        loading.value = false
    }
}

// 保存文件
const handleSave = async () => {
    if (!currentFilePath.value.trim()) {
        ElMessage.warning('请输入文件路径')
        return
    }

    if (!editor) {
        ElMessage.warning('编辑器未初始化')
        return
    }

    saving.value = true
    try {
        const content = editor.getValue()
        await fileApi.saveFile(currentFilePath.value, content)

        emit('update:filePath', currentFilePath.value)
        emit('saved', { filePath: currentFilePath.value, content })
        ElMessage.success('文件保存成功')

    } catch (error) {
        ElMessage.error('保存文件失败')
        console.error('保存文件失败:', error)
    } finally {
        saving.value = false
    }
}

// 编译文件
const handleCompile = async () => {
    if (!currentFilePath.value.trim()) {
        ElMessage.warning('请先保存文件后再编译')
        return
    }

    compiling.value = true
    try {
        await fileApi.compileFile(currentFilePath.value)
        emit('compiled', currentFilePath.value)
        ElMessage.success('编译成功')

    } catch (error) {
        ElMessage.error('编译失败')
        console.error('编译失败:', error)
    } finally {
        compiling.value = false
    }
}

// 清空编辑器
const handleClear = () => {
    if (editor) {
        editor.setValue('')
    }
}

// 文件路径变化处理
const handleFilePathChange = () => {
    emit('update:filePath', currentFilePath.value)
}

// 模板变化处理
const handleTemplateChange = () => {
    if (selectedTemplate.value && templateCodes[selectedTemplate.value]) {
        if (editor) {
            editor.setValue(templateCodes[selectedTemplate.value])
        }
    }
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
    if (editor && newValue !== editor.getValue()) {
        editor.setValue(newValue || '')
    }
})

watch(() => props.filePath, (newValue) => {
    currentFilePath.value = newValue
})

// 组件挂载
onMounted(() => {
    initEditor()

    // 监听窗口大小变化
    const handleResize = () => {
        if (editor) {
            setTimeout(() => {
                editor.layout()
            }, 100)
        }
    }

    window.addEventListener('resize', handleResize)
})

// 组件卸载
onBeforeUnmount(() => {
    // 清理事件监听器
    window.removeEventListener('resize', () => { })

    if (editor) {
        editor.dispose()
    }
})

// 暴露方法给父组件
defineExpose({
    getValue: () => editor?.getValue() || '',
    setValue: (value) => editor?.setValue(value || ''),
    getFilePath: () => currentFilePath.value,
    setFilePath: (path) => {
        currentFilePath.value = path
        emit('update:filePath', path)
    }
})
</script>

<style scoped>
.code-editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
}

.file-info {
    flex: 1;
    margin-right: 15px;
}

.file-path-input {
    max-width: 500px;
}

.editor-actions {
    display: flex;
    gap: 8px;
}

.editor-wrapper {
    position: relative;
    height: v-bind(height);
    overflow: hidden;
}

.monaco-editor {
    width: 100% !important;
    height: 100% !important;
    position: relative !important;
    overflow: hidden !important;
}

/* 解决Monaco Editor的CSS冲突 */
:deep(.monaco-editor) {
    font-family: 'Monaco', 'Courier New', monospace !important;
    line-height: 20px !important;
}

:deep(.monaco-editor .margin) {
    background-color: #1e1e1e !important;
}

:deep(.monaco-editor .monaco-editor-background) {
    background-color: #1e1e1e !important;
}

:deep(.monaco-editor .cursor) {
    background-color: #aeafad !important;
    border-left: 2px solid #aeafad !important;
    width: 2px !important;
}

:deep(.monaco-editor .current-line) {
    background-color: rgba(255, 255, 255, 0.05) !important;
}

:deep(.monaco-editor .line-numbers) {
    color: #858585 !important;
    font-size: 13px !important;
}

:deep(.monaco-editor .monaco-scrollable-element) {
    width: 100% !important;
    height: 100% !important;
}

/* 确保文本渲染正确 */
:deep(.monaco-editor .view-lines) {
    font-family: 'Monaco', 'Courier New', monospace !important;
    font-size: 14px !important;
    line-height: 20px !important;
    letter-spacing: 0px !important;
}

.template-selector {
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-top: 1px solid #dcdfe6;
}

/* 响应式布局 */
@media (max-width: 768px) {
    .editor-header {
        flex-direction: column;
        gap: 10px;
        align-items: stretch;
        padding: 10px;
    }

    .file-info {
        margin-right: 0;
        margin-bottom: 10px;
    }

    .file-path-input {
        max-width: 100%;
    }

    .editor-actions {
        justify-content: flex-end;
        flex-wrap: wrap;
        gap: 6px;
    }

    .editor-actions .el-button {
        font-size: 12px;
        padding: 6px 10px;
    }

    .template-selector {
        padding: 8px 10px;
    }

    .template-selector .el-select {
        width: 100% !important;
    }

    /* Monaco Editor 移动端优化 */
    :deep(.monaco-editor) {
        font-size: 12px !important;
    }

    :deep(.monaco-editor .view-lines) {
        font-size: 12px !important;
        line-height: 18px !important;
    }

    :deep(.monaco-editor .line-numbers) {
        font-size: 11px !important;
    }

    :deep(.monaco-editor .minimap) {
        display: none !important;
    }
}

@media (max-width: 480px) {
    .editor-header {
        padding: 8px;
    }

    .editor-actions {
        gap: 4px;
    }

    .editor-actions .el-button {
        font-size: 11px;
        padding: 4px 8px;
        min-width: auto;
    }

    .editor-actions .el-button span {
        display: none;
    }

    .template-selector {
        padding: 6px 8px;
    }

    /* 进一步优化Monaco Editor */
    :deep(.monaco-editor) {
        font-size: 11px !important;
    }

    :deep(.monaco-editor .view-lines) {
        font-size: 11px !important;
        line-height: 16px !important;
    }

    :deep(.monaco-editor .line-numbers) {
        font-size: 10px !important;
    }

    /* 隐藏一些不必要的UI元素 */
    :deep(.monaco-editor .margin-view-overlays) {
        display: none !important;
    }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
    .editor-actions .el-button {
        min-height: 44px;
        min-width: 44px;
    }

    :deep(.monaco-editor) {
        touch-action: pan-x pan-y;
    }
}

/* 横屏模式优化 */
@media (max-height: 500px) and (orientation: landscape) {
    .editor-wrapper {
        height: 300px !important;
    }

    .editor-header {
        padding: 6px 10px;
    }

    .template-selector {
        padding: 4px 10px;
    }
}
</style>